package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {


    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //发送短信的短信
    @GetMapping("/send/{phone}")
    public R  sendMsm(@PathVariable String phone){

        //从redis获取验证码， 如果获取到就直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            System.out.println("从redis获取验证码， 如果获取到就直接返回"+code);
            return R.ok();
        }

        //自己生成 没有能从redis获取到
        code = RandomUtil.getFourBitRandom();
        Map<String,Object>  param = new HashMap<>();
        param.put("code",code);
        System.out.println("发送短信验证码"+code);
        //发送短信
        boolean isSend=msmService.send(param,phone);

        if(isSend){
            //设置有效时间 5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("发送短信失败！");
        }
    }

}
